import json
import re
from zhipu_sdk import ZhipuAI
import uuid
import os
import requests
import requests
import uuid
import os
import mimetypes


def parse_markdown_json_content(text: str) -> dict | None:
    # 正则表达式匹配 ```json 和 ``` 之间的内容
    pattern = r"```json(.*?)```"
    match = re.search(pattern, text, re.DOTALL)

    if match:
        # 提取 JSON 字符串
        json_str = match.group(1).strip()
        # 解析 JSON 字符串
        data = json.loads(json_str)
        return data
    else:
        try:
            data = json.loads(text)
            return data
        except Exception as ex:
            return None


def file_parser_util(file_path) -> str:
    result, knowledge_type, df_dict, paragraph = ZhipuAI(api_key="").loader_file(file_path)
    strings = [data.text for data in result]
    combined_string = "".join(strings)
    return combined_string


def fetch_and_parse_file_content(resume_url: str) -> str:
    """
    从给定的 URL 下载简历文件并解析内容，支持自动清理本地临时文件。

    Args:
        resume_url (str): 简历文件的 URL。

    Returns:
        str: 解析的简历内容。

    Raises:
        Exception: 下载或解析文件失败时抛出异常。
    """
    # 生成唯一文件路径以避免冲突
    unique_id = str(uuid.uuid4())
    local_file_path = f"/tmp/{unique_id}"

    try:
        # 下载文件
        response = requests.get(resume_url)
        if response.status_code != 200:
            raise Exception(f"Failed to fetch the resume from URL: {response.status_code}")

        # 自动检测文件类型并设置正确的文件扩展名
        content_type = response.headers.get('content-type')
        extension = mimetypes.guess_extension(content_type)
        if extension is None:
            raise Exception("Could not determine the file type")
        local_file_path += extension

        # 将文件保存到本地
        with open(local_file_path, "wb") as file:
            file.write(response.content)

        # 使用 file_parser_util 处理文件并提取内容
        resume_text = file_parser_util(file_path=local_file_path)
        return resume_text

    except Exception as e:
        raise Exception(f"Error during resume processing: {e}")

    finally:
        # 确保临时文件被清理
        if os.path.exists(local_file_path):
            os.remove(local_file_path)
# res = file_parser_util('/Users/xiaoyaojun/Desktop/demos/ai-interview/graph/刘鸽_三年工作经验_简历.docx')
#
# print(res)
